/*
 * Copyright 2022 Nightingale Team
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
import React, { useEffect, useContext } from 'react';
import { Switch, Route, useLocation, Redirect, useHistory } from 'react-router-dom';
import querystring from 'query-string';
import _ from 'lodash';
import { getMenuPerm } from '@/services/common';
import { IS_ENT } from '@/utils/constant';
import { CommonStateContext } from '@/App';
import Page403 from '@/pages/notFound/Page403';
import OutOfService from '@/pages/notFound/OutOfService';
import NotFound from '@/pages/notFound';
import Login from '@/pages/login';
import Overview from '@/pages/login/overview';
import LoginCallback from '@/pages/loginCallback';
import LoginCallbackCAS from '@/pages/loginCallback/cas';
import LoginCallbackOAuth from '@/pages/loginCallback/oauth';
import AlertRules, { Add as AlertRuleAdd, Edit as AlertRuleEdit } from '@/pages/alertRules';
import Profile from '@/pages/account/profile';
import { List as Dashboard, Detail as DashboardDetail, Share as DashboardShare } from '@/pages/dashboard';
import { getDefaultThemeMode } from '@/pages/dashboard/Detail/utils';
import Chart from '@/pages/chart';
import Groups from '@/pages/user/groups';
import Users from '@/pages/user/users';
import Business from '@/pages/user/business';
import { Metric as MetricExplore, Log as LogExplore } from '@/pages/explorer';
import IndexPatterns, { Fields as IndexPatternFields } from '@/pages/log/IndexPatterns';
import ObjectExplore from '@/pages/monitor/object';
import Shield, { Add as AddShield, Edit as ShieldEdit } from '@/pages/warning/shield';
import Subscribe, { Add as SubscribeAdd, Edit as SubscribeEdit } from '@/pages/warning/subscribe';
import Event from '@/pages/event';
import EventDetail from '@/pages/event/detail';
import historyEvents from '@/pages/historyEvents';
import Targets from '@/pages/targets';
import Demo from '@/pages/demo';
import TaskTpl from '@/pages/taskTpl';
import TaskTplAdd from '@/pages/taskTpl/add';
import TaskTplDetail from '@/pages/taskTpl/detail';
import TaskTplModify from '@/pages/taskTpl/modify';
import TaskTplClone from '@/pages/taskTpl/clone';
import Task from '@/pages/task';
import TaskAdd from '@/pages/task/add';
import TaskResult from '@/pages/task/result';
import TaskDetail from '@/pages/task/detail';
import Version from '@/pages/help/version';
import Servers from '@/pages/help/servers';
import Datasource, { Form as DatasourceAdd } from '@/pages/datasource';
import RecordingRule, { Add as RecordingRuleAdd, Edit as RecordingRuleEdit } from '@/pages/recordingRules';
import TraceExplorer, { Dependencies as TraceDependencies } from '@/pages/traceCpt/Explorer';
import Permissions from '@/pages/permissions';
import SSOConfigs from '@/pages/help/SSOConfigs';
import NotificationTpls from '@/pages/help/NotificationTpls';
import NotificationSettings from '@/pages/help/NotificationSettings';
import MigrateDashboards from '@/pages/help/migrate';
import VariableConfigs from '@/pages/variableConfigs';
import SiteSettings from '@/pages/siteSettings';
import { dynamicPackages, Entry, dynamicPages } from '@/utils';
// @ts-ignore
import { Jobs as StrategyBrain } from 'plus:/datasource/anomaly';
// @ts-ignore
import plusLoader from 'plus:/utils/loader';
// @ts-ignore
import useIsPlus from 'plus:/components/useIsPlus';

const Packages = dynamicPackages();
let lazyRoutes = Packages.reduce((result: any, module: Entry) => {
  return (result = result.concat(module.routes));
}, []);

const lazyPagesRoutes = _.reduce(
  dynamicPages(),
  (result: any, module: Entry) => {
    return (result = result.concat(module.routes));
  },
  [],
);

function RouteWithSubRoutes(route) {
  return (
    <Route
      path={route.path}
      render={(props) => (
        // pass the sub-routes down to keep nesting
        <route.component {...props} routes={route.routes} data-oid='fccwdk_' />
      )}
      data-oid='8xzkrwz'
    />
  );
}

export default function Content() {
  const location = useLocation();
  const history = useHistory();
  const isPlus = useIsPlus();
  const { profile, siteInfo, perms } = useContext(CommonStateContext);

  useEffect(() => {
    /**
     * 这里是一个很脆弱的权限控制，期望的效果是菜单配置的路径和权限点匹配，如果没有权限则重定向到 403 页面
     * 但是目前无法把菜单配置和perms权限点一一对应
     * 所以这里现在只能通过白名单的方式来单独处理个别未配置权限点的路径
     * /docs/等页面不进行权限校验
     */
    if (profile?.roles?.length > 0 && !_.includes(['/', '/account/profile/info', '/account/profile/pwd'], location.pathname) && !location.pathname.includes('/docs/')) {
      if (profile?.roles.indexOf('Admin') === -1) {
        // 如果没有权限则重定向到 403 页面
        if (
          _.every(perms, (item) => {
            return location.pathname.indexOf(item) === -1;
          })
        ) {
          history.push('/403');
        }
      }
    }
  }, []);

  return (
    <div className='content' data-oid='0ppv194'>
      <Switch data-oid='dz_.cke'>
        <Route path='/demo' component={Demo} data-oid='82:0q8:' />
        <Route path='/overview' component={Overview} data-oid='3togw:p' />
        <Route path='/login' component={Login} exact data-oid='3zycnra' />
        <Route path='/callback' component={LoginCallback} exact data-oid='10j2ffh' />
        <Route path='/callback/cas' component={LoginCallbackCAS} exact data-oid='05cqnbn' />
        <Route path='/callback/oauth' component={LoginCallbackOAuth} exact data-oid='828uz8f' />
        <Route path='/metric/explorer' component={MetricExplore} exact data-oid='nni81vd' />
        <Route path='/log/explorer' component={LogExplore} exact data-oid='51sv.vx' />
        <Route path='/log/index-patterns' component={IndexPatterns} exact data-oid='um7_8m0' />
        <Route path='/log/index-patterns/:id' component={IndexPatternFields} exact data-oid='y-ow-uo' />
        <Route path='/object/explorer' component={ObjectExplore} exact data-oid='ouxmujf' />
        <Route path='/busi-groups' component={Business} data-oid='44rq6g3' />
        <Route path='/users' component={Users} data-oid='f99r7ge' />
        <Route path='/user-groups' component={Groups} data-oid='pzr2-rr' />
        <Route path='/account/profile/:tab' component={Profile} data-oid='yimwy.-' />

        <Route path='/dashboard/:id' exact component={DashboardDetail} data-oid='81z3k_n' />
        <Route path='/dashboards/:id' exact component={DashboardDetail} data-oid='6njgvb3' />
        <Route path='/dashboards/share/:id' component={DashboardShare} data-oid='.yv_cwu' />
        <Route path='/dashboards' component={Dashboard} data-oid='2ex54_b' />
        <Route path='/chart/:ids' component={Chart} data-oid='fx_upe3' />

        <Route exact path='/alert-rules/add/:bgid' component={AlertRuleAdd} data-oid='9j25hbk' />
        <Route exact path='/alert-rules/edit/:id' component={AlertRuleEdit} data-oid='szqsp8_' />
        <Route exact path='/alert-rules' component={AlertRules} data-oid='4d4bjyz' />
        <Route exact path='/alert-rules/brain/:id' component={StrategyBrain} data-oid='sqwqcq9' />
        <Route exact path='/alert-mutes' component={Shield} data-oid='-r..bsx' />
        <Route exact path='/alert-mutes/add/:from?' component={AddShield} data-oid='au3:ut4' />
        <Route exact path='/alert-mutes/edit/:id' component={ShieldEdit} data-oid='z263ita' />
        <Route exact path='/alert-subscribes' component={Subscribe} data-oid='ngqbb2.' />
        <Route exact path='/alert-subscribes/add' component={SubscribeAdd} data-oid='vbbbovp' />
        <Route exact path='/alert-subscribes/edit/:id' component={SubscribeEdit} data-oid='kwcabmw' />

        {!isPlus && [
          <Route key='recording-rules' exact path='/recording-rules/:id?' component={RecordingRule} data-oid='9gm.oh5' />,
          <Route key='recording-rules-add' exact path='/recording-rules/add/:group_id' component={RecordingRuleAdd} data-oid='wevowck' />,
          <Route key='recording-rules-edit' exact path='/recording-rules/edit/:id' component={RecordingRuleEdit} data-oid='y_4bulo' />,
        ]}

        <Route exact path='/alert-cur-events' component={Event} data-oid='sd82j6s' />
        <Route exact path='/alert-his-events' component={historyEvents} data-oid='io5iq15' />
        <Route exact path='/alert-cur-events/:eventId' component={EventDetail} data-oid=':ix:uag' />
        <Route exact path='/alert-his-events/:eventId' component={EventDetail} data-oid='b320k63' />
        <Route exact path='/targets' component={Targets} data-oid='k:rvmwg' />

        <Route exact path='/job-tpls' component={TaskTpl} data-oid='7qbeew7' />
        <Route exact path='/job-tpls/add' component={TaskTplAdd} data-oid='i1y:zpz' />
        <Route exact path='/job-tpls/add/task' component={TaskAdd} data-oid='su4o20q' />
        <Route exact path='/job-tpls/:id/detail' component={TaskTplDetail} data-oid='urg2olx' />
        <Route exact path='/job-tpls/:id/modify' component={TaskTplModify} data-oid='fsbzgeq' />
        <Route exact path='/job-tpls/:id/clone' component={TaskTplClone} data-oid=':56jnu:' />
        <Route exact path='/job-tasks' component={Task} data-oid='si:.tee' />
        <Route exact path='/job-tasks/add' component={TaskAdd} data-oid='1guy.fs' />
        <Route exact path='/job-tasks/:id/result' component={TaskResult} data-oid='4mkjdux' />
        <Route exact path='/job-tasks/:id/detail' component={TaskDetail} data-oid='94zdlat' />

        <Route exact path='/help/version' component={Version} data-oid='b:p1c-w' />
        <Route exact path='/help/servers' component={Servers} data-oid='m5j4p44' />
        <Route exact path='/help/source' component={Datasource} data-oid='u-_w0kj' />
        <Route exact path='/help/source/:action/:type' component={DatasourceAdd} data-oid='qz:2c8h' />
        <Route exact path='/help/source/:action/:type/:id' component={DatasourceAdd} data-oid='5mwy4xv' />
        <Route exact path='/help/sso' component={SSOConfigs} data-oid='s6:i5zr' />
        <Route exact path='/help/notification-tpls' component={NotificationTpls} data-oid='60tgf8u' />
        <Route exact path='/help/notification-settings' component={NotificationSettings} data-oid='9ui8ild' />
        <Route exact path='/help/migrate' component={MigrateDashboards} data-oid='_y9t:eg' />
        <Route exact path='/help/variable-configs' component={VariableConfigs} data-oid='65yo8qb' />

        <Route exact path='/trace/explorer' component={TraceExplorer} data-oid='aactvj4' />
        <Route exact path='/trace/dependencies' component={TraceDependencies} data-oid='7kudefn' />

        <Route exact path='/permissions' component={Permissions} data-oid='kvgkhtv' />

        <Route exact path='/site-settings' component={SiteSettings} data-oid='u:_c8et' />

        {lazyRoutes.map((route, i) => (
          <RouteWithSubRoutes key={i} {...route} data-oid='mkape2m' />
        ))}
        {_.map(lazyPagesRoutes, (route, i) => (
          <RouteWithSubRoutes key={i} {...route} data-oid='ocm21.e' />
        ))}
        {_.map(plusLoader.routes, (route, i) => (
          <RouteWithSubRoutes key={i} {...route} data-oid='4wkfs1_' />
        ))}
        <Route path='/' exact data-oid='zvpagm0'>
          <Redirect to={siteInfo?.home_page_url || '/metric/explorer'} data-oid='b_upcpu' />
        </Route>
        <Route path='/403' component={Page403} data-oid='vj83zv3' />
        <Route path='/404' component={NotFound} data-oid='067ssy3' />
        <Route path='/out-of-service' component={OutOfService} data-oid='6lar381' />
        <Route path='*' component={NotFound} data-oid='0o65-1w' />
      </Switch>
    </div>
  );
}
